#include "../include/recvComm.h"


// 一次性接收
int recv_n_comm(int netfd, void *buf, int length){
    ssize_t cur_len = 0;
    char *p = (char *)buf;
    while(cur_len < length){
        ssize_t sret = recv(netfd, p+cur_len, length-cur_len, 0); 
        if(sret == 0)
        {
            return -1;
        }
        cur_len += sret;
    }   
    return 0;
}

int recv_comm(int netfd, char *commPath, TYPE *curComm){
    commTrain_t train;
    // 接收命令
    int ret = recv_n_comm(netfd, &train.type, sizeof(train.type));
    if(ret == -1)
    {
        return -1;
    }
    /* printf("train.type = %d\n", train.type); */
    *curComm = train.type;
    // 循环接收命令行
    while(1){
        bzero(train.data, sizeof(train.data));
        recv_n_comm(netfd, &train.type, sizeof(train.type));
        recv_n_comm(netfd, &train.length, sizeof(train.length));
        if(train.type == DATA && train.length == 0){
            break;
        }
        recv_n_comm(netfd, &train.data, train.length);
        strcat(commPath, train.data);
    }
    return 0;
}

int do_comm(int netfd, commandStack_t *curPath){
    /* print_stack(curPath); */
    TYPE curComm;
    char command_path[1024] = {0};
    char res[100];
    int ret = recv_comm(netfd, command_path, &curComm);
    if(ret == -1)
    {
        close(netfd);
        return 0;
    }
    /* printf("command_path: %s\n", command_path); */
    /* printf("用户名是%s\n", curPath->username); */
    switch(curComm){
    case DATA:
        break;
    case CD:
        do_cd(netfd, curPath,command_path);
        printf("do cd\n");
        break;
    case LS:
        do_ls(netfd, curPath,command_path);
        printf("do ls\n");
        break;
    case PUTS:
        s_recv_up(netfd, curPath);
        strcpy(res,"上传成功\n");
        trans_res(netfd,res); 
        printf("do puts\n");
        break;
    case GETS:
        s_download(netfd,curPath);
        strcpy(res,"下载成功\n");
        trans_res(netfd,res); 
        printf("do gets\n");
        break;
    case REMOVE:
        do_rmdir(netfd, curPath, command_path);
        printf("do remove\n");
        break;
    case PWD:
        do_pwd(netfd, curPath, command_path);
        printf("do pwd\n");
        break;
    case MKDIR:
        do_mkdir(netfd, curPath, command_path);
        printf("do mkdir\n");
        break;
    
    }
    return 0;
}
